import { Footer } from '@/components';
import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import { history, useModel, Helmet } from '@umijs/max';
import {Alert, Image, message, Space, Tabs} from 'antd';
import Settings from '../../../../config/defaultSettings';
import React, {useEffect, useRef, useState} from 'react';
import { flushSync } from 'react-dom';
import { createStyles } from 'antd-style';
import {fetchCaptchaToBase64, sendCaptcha, userLogin} from "@/services/ant-design-pro/userController";
import {ProFormInstance} from "@ant-design/pro-form/lib";
const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});
const ActionIcons = () => {
  const { styles } = useStyles();
  return (
    <>
      <AlipayCircleOutlined key="AlipayCircleOutlined" className={styles.action} />
      <TaobaoCircleOutlined key="TaobaoCircleOutlined" className={styles.action} />
      <WeiboCircleOutlined key="WeiboCircleOutlined" className={styles.action} />
    </>
  );
};
const LoginMessage: React.FC<{
  content: string;
}> = ({ content }) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};
const Login: React.FC = () => {
  // const [userLoginState, setUserLoginState] = useState<API.UserEntity>({});
  const [loginType, setLoginType] = useState<string>('PASSWORD');
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const loginFormRef = useRef<ProFormInstance>()
  const fetchUserLoginInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const [loginCaptchaConfig,setLoginCaptchaConfig] = useState<API.LoginCaptchaVO>()
  const fetchLoginCaptcha = () => {

    fetchCaptchaToBase64().then(res=>{
      if (res?.code === 200){
        setLoginCaptchaConfig({
          ...res?.data
        })
        return;
      }
      message.error(res?.message)
    })

  }
  const handleSubmit = async (values: any) => {
    try {
      // 登录
      const msg = await userLogin({
        ...values,
        loginType,
        loginCaptchaKey:loginCaptchaConfig?.key
      });
      if (msg.code === 200) {
        const defaultLoginSuccessMessage = '登录成功！';
        message.success(defaultLoginSuccessMessage);
        if (!msg?.data){
          message.error(msg.message)
        }
        localStorage.setItem("X-Token",msg.data as string)
        await fetchUserLoginInfo();
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
        return;
      }
      message.error(msg.message);
      // 如果失败去设置用户错误信息
      // setUserLoginState(msg?.data);
    } catch (error) {
      const defaultLoginFailureMessage = '登录失败，请重试！';
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };

  /**
   * 发送邮箱验证码
   */
  const sendEmailCaptcha = async () => {
    const userAccount = loginFormRef?.current?.getFieldValue("userAccount");
    const result = await sendCaptcha({
      userAccount,
    });
    if (result.code === 200) {
      message.success('获取验证码成功！');
      return;
    }
    message.error(result?.message)
  }

  useEffect(()=>{
    fetchLoginCaptcha()
  },[])

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {'登录'}- {Settings.title}
        </title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg" />}
          title="Ant Design"
          subTitle={'Ant Design 是西湖区最具影响力的 Web 设计规范'}
          formRef={loginFormRef}
          initialValues={{
            autoLogin: true,
          }}
          actions={['其他登录方式 :', <ActionIcons key="icons" />]}
          onFinish={async (values) => {
            await handleSubmit(values as API.UserLoginRequest);
          }}
        >
          <Tabs
            activeKey={loginType}
            onChange={setLoginType}
            centered
            items={[
              {
                key: 'PASSWORD',
                label: '账户密码登录',
              },
              {
                key: 'CAPTCHA',
                label: '邮箱登录',
              },
            ]}
          />

          {status === 'error' && loginType === 'PASSWORD' && (
            <LoginMessage content={'错误的用户名和密码(admin/ant.design)'} />
          )}
          {loginType === 'PASSWORD' && (
            <>
              <ProFormText
                name="userAccount"
                initialValue="750321038@qq.com"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={'用户名: admin or user'}
                rules={[
                  {
                    required: true,
                    message: '用户名是必填项！',
                  },
                ]}
              />
              <ProFormText.Password
                name="userPassword"
                initialValue="12345678"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'密码: ant.design'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                ]}
              />
              <Space.Compact>
                <ProFormText
                  name="loginCaptchaCode"
                  placeholder="请输入验证码"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined />,
                  }}
                />
                <div onClick={fetchLoginCaptcha}>
                  <Image height={40} preview={false} src={loginCaptchaConfig?.base64}></Image>
                </div>
              </Space.Compact>
            </>
          )}

          {status === 'error' && loginType === 'CAPTCHA' && <LoginMessage content="验证码错误" />}
          {loginType === 'CAPTCHA' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined />,
                }}
                name="userAccount"
                initialValue='750321038@qq.com'
                placeholder={'请输入邮箱帐号！'}
                rules={[
                  {
                    required: true,
                    message: '邮箱帐号是必填项！',
                  },
                  {
                    pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
                    message: '不合法的邮箱帐号！',
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder={'请输入验证码！'}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} ${'秒后重新获取'}`;
                  }
                  return '获取验证码';
                }}
                name="captcha"
                rules={[
                  {
                    required: true,
                    message: '验证码是必填项！',
                  },
                ]}
                onGetCaptcha={sendEmailCaptcha}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              自动登录
            </ProFormCheckbox>
            <a
              style={{
                float: 'right',
              }}
            >
              忘记密码 ?
            </a>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};
export default Login;
